import { createSlice } from "@reduxjs/toolkit";
import trademarkApi from "@/api/trademark";
import type { PageListData } from "@/api/trademark";
import type { TradeMarkData } from "@/api/trademark";

export interface GetPageParams {
  page: number;
  limit: number;
  // type: string
}

// 定义初始化的数据
const initialState: PageListData = {
  records: [],
  total: 0,
  size: 0,
  current: 0,
  searchCount: true,
  pages: 0,
};

const tradeMarkSlice = createSlice({
  name: "trademark",
  initialState,
  reducers: {
    // 分页列表的数据
    getPageList: (state, action) => {
      // redux的数据不可以直接修改-直接修改会出问题
      state = Object.assign(state, action.payload);
    },
    // 添加数据-将数据push到新的数据当中(改变数组的长度不会改变数组的地址值)
    addTrade: (state, action) => {
      state.records.push(action.payload);
    },
    // 修改数据-根据id寻找对应的数据进行修改
    updateTrade: (state, { payload }) => {
      state.records.forEach((item) => {
        if (item.id === payload.id) {
          item.tmName = payload.tmName;
          item.logoUrl = payload.logoUrl;
        }
      });
    },
    // 删除数据-根据id进行删除
    deleteTrade: (state, { payload }) => {
      state.records.filter((item) => {
        if (item.id !== payload.id) {
          return true;
        }
      });
      console.log(state.records.length, "slice");
    },
  },
});

// 获取并暴露action
export const { getPageList, addTrade, updateTrade, deleteTrade } =
  tradeMarkSlice.actions;

//书写发送请求获取tradeMarkList异步请求的函数
export const asyncGetPageList = (payload: GetPageParams) => {
  return async (dispatch: any) => {
    try {
      let result = await trademarkApi.pageList(payload.page, payload.limit);
      dispatch(getPageList(result));
    } catch (error) {
      return Promise.reject(error);
    }
  };
};

// 书写添加tradeMark数据的请求
export const asyncAddTradeMark = (payload: TradeMarkData) => {
  return async (dispatch: any) => {
    try {
      await trademarkApi.addTradeMark(payload);
      dispatch(addTrade(payload));
    } catch (error) {
      return Promise.reject(error);
    }
  };
};

// 书写修改tradeMark数据的请求
export const asyncUpdateTrade = (payload: TradeMarkData) => {
  return async (dispatch: any) => {
    try {
      await trademarkApi.updateTradeMark(payload);
      dispatch(updateTrade(payload));
    } catch (error) {
      return Promise.reject(error);
    }
  };
};

// 书写删除TradeMark数据的请求
export const asyncRemove = (payload: number) => {
  return async (dispatch: any) => {
    try {
      await trademarkApi.deleteTrademark(payload);
      dispatch(deleteTrade(payload));
    } catch (error) {
      return Promise.reject(error);
    }
  };
};

export default tradeMarkSlice.reducer;
